Repository navigation
Give types with an implicit numeric conversion Python's number protocol - #151
Open
jhonabreul wants to merge 7 commits into
Open
jhonabreul wants to merge 7 commits into
jhonabreul wants to merge 7 commits into
Conversation
… the instance C# extension methods were only reachable from Python through their static class, so instance-style calls such as order_status.is_open() failed with AttributeError. Extension methods declared in non-framework assemblies are now indexed during the assembly scan and bound as members of the type they extend, including interface targets on implementing classes. The binder passes the instance as the first argument when an extension method is called through it. Real members with the same name win, and open generic targets are skipped since the binder cannot infer them from the instance.
Python operators never consult C# implicit conversions, so a type convertible to decimal or double still raised TypeError on addition, comparison and float(). Such types now get arithmetic, comparison, __float__ and __int__ methods delegating to the conversion, grafted at class binding the same way EnumOps is for enums. Operators the type declares itself are kept.
This was referenced Oct 14, 2026
Targets made only of framework types are shared by countless classes: extensions on object reached every CLR object, and Accord.Math alone added ~600 methods to each primitive array type. Across Lean's assemblies the index shrinks from 16487 to 653 methods. Such extensions keep their static form. Assemblies without the compiler's assembly-level [Extension] marker are skipped up front, as C# does, and binding a class only walks its interfaces when an interface target was indexed. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Everything went through double, so integral conversions lost precision past 2**53 and returned floats where Python gives ints. Values now behave like the Python number their conversion maps to: exact ints for integral conversions (unbounded, like Python), floats for floating point and decimal ones. - operands arrive as PyObject: ints beyond Int32 failed the binder's object conversion, and numbers implementing __index__ or __float__ (numpy scalars, other CLR types with a conversion) are read too; anything else returns NotImplemented so Python raises its usual TypeError - division by zero raises ZeroDivisionError instead of returning infinity - int() truncates decimals exactly and raises ValueError/OverflowError on NaN/infinity - comparisons between instances of an IComparable type use its own ordering, as they did before the number protocol was added - inherited operators keep winning over the synthesized ones, as in C#; OperatorMethod shares the filtered list, or the inherited slot recursed Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Member
Review follow-up: pushed 4444105, 62447d5 and ab9cc61Where:
What and why
How
Performance: both versions were timed with the same embed test. Arithmetic went from about 1.7–1.8 µs to 1.2 µs per op, and comparisons from 2.8 µs to 1.6 µs, because there's now one overload per direction instead of three. A plain property read is about 0.2 µs for reference. These timings are rough: the full suite was running at the same time. Tests
🤖 Generated with Claude Code |
…form [EditorBrowsable(EditorBrowsableState.Never)] hides a member from IntelliSense while keeping it callable. Binding such extension methods to the instance would advertise them anyway, so those methods, and all the extension methods of a class marked so, keep their static form only. It lets a library hide plumbing helpers, like Lean's IAlgorithm extensions, from the instance with a standard attribute. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What does this implement/fix? Explain your changes.
Stacked on #150; the last two commits are this change.
A C# type with an implicit conversion to a number is usable as a number in C#, but not in Python:
Cause: Python evaluates
a + bthroughtype(a).__add__, pythonnet wires those slots from C# operator methods only, and anop_Implicitconversion is never consulted by an operator expression.The change:
ImplicitNumericOps<T>is an[Ops]class likeEnumOps<T>: arithmetic, comparison, unary negation,__float__and__int__methods delegating to the type's implicit numeric conversion.ClassManager.GetClassInfografts those methods onto any type whose public staticop_Implicitreturns a numeric type, skipping operator names the type declares itself.OperatorMethod.GetOperatorCandidatesincludes them soFixupSlotswires the number slots, and a new__float__slot definition maps tonb_float.1 < xontox > 1by itself.Does this close any currently open issues?
No.
Any other comments?
Tests, in
TestImplicitNumericOperators:sum,maxandsortedover convertible instances.float()on a decimal-backed type,float()andint()on a double-backed type.+keeps it, while the undeclared-is synthesized.__add__or__float__.